import './shims/node-util-extend-shim'

// 优先导入移动端适配（必须在其他模块之前）
import mobileAdapter from './utils/mobile-adapter'
import './styles/mobile-base.css'

// 初始化移动端适配
mobileAdapter.initMobileAdapter()

import Vue from 'vue'
import App from './App.vue'
import store from './store'
import api from './api'
import Navigation from './utils/navigation'
import UniPopup from './components/uni-popup.vue'
import CustomTabBar from './components/CustomTabBar.vue'
import SettingsModal from './components/SettingsModal.vue'
import UserInfoBar from './components/UserInfoBar.vue'

Vue.config.productionTip = false

// 全局注册组件
Vue.component('uni-popup', UniPopup)
Vue.component('CustomTabBar', CustomTabBar)
Vue.component('SettingsModal', SettingsModal)
Vue.component('UserInfoBar', UserInfoBar)

// 将API模块挂载到Vue原型上
Vue.prototype.$api = api

// 全局物品更新钩子：供请求层在解析成功后调用，避免循环依赖
window.__updateItemsFromResponse = function(itemsArray) {
  try {
    if (Array.isArray(itemsArray) && itemsArray.length > 0) {
      store.dispatch('items/applyItemsFromArray', itemsArray)
    }
  } catch (e) {
    console.warn('Global items update failed:', e)
  }
}

// 全局混入uni-app API
Vue.mixin({
  // 移除uni对象，避免与全局uni冲突
})

// 全局注册uni对象
window.uni = {
  // 页面导航方法 - 统一使用hash路由
  navigateTo: (options) => {
    try {
      window.location.hash = options.url
    } catch (error) {
      console.error('Navigation failed:', error)
    }
  },
  reLaunch: (options) => {
    try {
      window.location.hash = options.url
    } catch (error) {
      console.error('ReLaunch failed:', error)
    }
  },
  switchTab: (options) => {
    try {
      // 验证tabbar页面路径
      const validTabPaths = [
        '/pages/main/index',
        '/pages/adventure/index', 
        '/pages/opportunity/index',
        '/pages/market/index',
        '/pages/system/index'
      ]
      
      if (validTabPaths.includes(options.url)) {
        window.location.hash = options.url
        if (options.success) options.success()
      } else {
        console.error('Invalid tab path:', options.url)
        if (options.fail) options.fail({ errMsg: 'Invalid tab path' })
      }
    } catch (error) {
      console.error('SwitchTab failed:', error)
      if (options.fail) options.fail({ errMsg: error.message })
    }
  },
  navigateBack: (options) => {
    try {
      window.history.back()
    } catch (error) {
      console.error('NavigateBack failed:', error)
    }
  },
  
  // 页面栈方法 - H5环境下的模拟实现
  getCurrentPages: () => {
    // 在H5环境下返回模拟的页面栈
    const currentPath = (window.location.hash.slice(1) || '/pages/main/index').split('?')[0]
    const options = (typeof Navigation !== 'undefined' && Navigation.getCurrentParams) ? Navigation.getCurrentParams() : {}
    return [{
      route: currentPath,
      options
    }]
  },
  
  // UI交互方法 - 使用全局消息组件
  showToast: (options) => {
    // 显示提示信息 - 使用全局消息组件而不是alert
    if (options.title) {
      const type = options.icon === 'success' ? 'success' : 
                   options.icon === 'error' ? 'error' : 
                   options.icon === 'none' ? 'error' : 'info'
      const duration = options.duration || 3000
      
      if (typeof window !== 'undefined' && typeof window.showMessage === 'function') {
        window.showMessage(options.title, type, duration)
      } else {
        // 降级处理
        console.log('Toast:', options.title)
      }
    }
  },
  showModal: (options) => {
    // 显示模态框
    if (options.content) {
      return options.showCancel === false ? 
        alert(options.content) : 
        confirm(options.content)
    }
  },
  showActionSheet: (options) => {
    // 显示操作菜单
    if (options.itemList && options.itemList.length > 0) {
      const choice = prompt('请选择:\n' + options.itemList.map((item, index) => `${index}: ${item}`).join('\n'))
      if (choice !== null && options.success) {
        options.success({ tapIndex: parseInt(choice) })
      }
    }
  },
  
  // 存储方法
  getStorageSync: (key) => localStorage.getItem(key),
  setStorageSync: (key, value) => localStorage.setItem(key, value),
  request: (options) => {
    // 为了兼容性，保留原有的uni.request方法
    // 但建议使用新的API模块
    return new Promise((resolve, reject) => {
      import('@/api').then(({ request }) => {
        request({
          url: options.url,
          method: options.method || 'POST',
          data: options.data || {}
        })
        .then(data => {
          const response = { data }
          if (options.success) {
            options.success(response)
          }
          resolve(response)
        })
        .catch(error => {
          if (options.fail) {
            options.fail(error)
          }
          reject(error)
        })
      })
      .catch(error => {
        if (options.fail) {
          options.fail(error)
        }
        reject(error)
      })
    })
  }
}

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')

// 为 H5 提供 showToast 兼容实现，使用全局消息组件
window.uni.showToast = (options = {}) => {
  try {
    const text = options.title || ''
    if (!text) return
    
    // 使用全局消息组件而不是alert
    const type = options.icon === 'success' ? 'success' : 
                 options.icon === 'error' ? 'error' : 
                 options.icon === 'none' ? 'error' : 'info'
    const duration = options.duration || 3000
    
    if (typeof window.showMessage === 'function') {
      window.showMessage(text, type, duration)
    } else {
      // 降级处理
      console.log('Toast:', text)
    }
    
    if (typeof options.success === 'function') options.success({})
  } catch (error) {
    console.warn('showToast failed:', error)
    if (typeof options.fail === 'function') options.fail(error)
  }
}